<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="89px">
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="searchParam.datesSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            @change="getChangeDate"
          />
        </el-form-item>
        <!-- <el-form-item label="供应商编号">
          <el-input
            v-model="searchParam.partnerCode"
            placeholder="请输入供应商编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="物料编号">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入供应商编号"
            clearable
          />
        </el-form-item> -->
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchParam.partnerName"
            placeholder="请输入供应商编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入供应商名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="计划状态">
          <el-select
            v-model="searchParam.demandStatus"
            placeholder="请选择计划状态"
            clearable
          >
            <el-option
              v-for="item in demandStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            展示
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" class="ml-3" @click="downLoad">
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <!-- 导入计划 -->
      <ImportExcel ref="weekImportRef" />

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        :span-method="(param) => objectSpanMethod(param, 3, 4)"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
      >
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index }">
            <span>{{ $index / 3 + 1 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="物料编号"
          prop="materialCode"
          width="150"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        /> -->
        <el-table-column
          label="物料"
          prop="materialCode"
          width="150"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        >
          <template #default="{ row }">
            {{ row.materialCode }}
            <br />
            {{ row.materialName }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="供应商编号"
          prop="partnerCode"
          min-width="100"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        />
        <el-table-column
          label="供应商名称"
          prop="partnerName"
          min-width="150"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        /> -->
        <el-table-column
          label="供应商"
          prop="partnerCode"
          width="150"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        >
          <template #default="{ row }">
            {{ row.partnerCode }}
            <br />
            {{ row.partnerName }}
          </template>
        </el-table-column>
        <el-table-column
          label="卸货口"
          prop="dischargeHatchName"
          min-width="90"
          show-overflow-tooltip
          fixed
          class-name="padding012"
        >
          <template #default="{ row }">
            {{
              row.dischargeHatchAbbr
                ? row.dischargeHatchAbbr
                : row.dischargeHatchName
            }}
          </template>
        </el-table-column>
        <el-table-column label="过程" width="60" fixed>
          <template #default="{ $index }">
            <span class="text-[13px]" v-if="($index + 1) % 3 == 1">计划</span>
            <span class="text-[13px]" v-if="($index + 1) % 3 == 2">反馈</span>
            <span class="text-[13px]" v-if="($index + 1) % 3 == 0">确认</span>
          </template>
        </el-table-column>
        <el-table-column label="总数量" width="90" fixed>
          <template #default="{ row, $index }">
            <span v-if="($index + 1) % 3 == 1">{{
              row.demandTotalQuantity != 0 ? row.demandTotalQuantity : ""
            }}</span>
            <span v-if="($index + 1) % 3 == 2">{{
              row.feedbackTotalQuantity != 0 ? row.feedbackTotalQuantity : ""
            }}</span>
            <span v-if="($index + 1) % 3 == 0">{{
              row.confirmTotalQuantity != 0 ? row.confirmTotalQuantity : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(dayItem, dayIndex) in intervalDayList"
          :key="dayIndex"
          :label="`${dayItem.date}`"
          :label-class-name="
            dayItem.week == 0 || dayItem.week == 6 ? 'bg-free' : ''
          "
          min-width="60"
        >
          <template #default="{ row, $index }">
            <div
              :style="{
                backgroundColor:
                  inConsistent(row, $index, dayIndex) == ''
                    ? ''
                    : inConsistent(row, $index, dayIndex),
              }"
            >
              <!-- 计划数量 -->
              <div v-if="($index + 1) % 3 == 1">
                <!-- <span
                  class="cursor-pointer cellNumber"
                  @click="openAddGoods(row.scheduleList[dayIndex])"
                  >{{
                    row.scheduleList[dayIndex]?.demandStatus == 3
                      ? row.scheduleList[dayIndex]?.confirmQuantity
                      : row.scheduleList[dayIndex]?.demandQuantity || ""
                  }}</span
                > -->
                <span>{{ row.scheduleList[dayIndex]?.demandQuantity }}</span>
              </div>
              <!-- 反馈数量 -->
              <div v-if="($index + 1) % 3 == 2">
                <span v-if="row.id !== '-999'">{{
                  row.feedbackList[dayIndex]?.feedbackTotal || ""
                }}</span>
                <span v-else>{{
                  row.feedbackList[dayIndex]?.feedbackTotal
                }}</span>
              </div>
              <!-- 确认数量 -->
              <div v-if="($index + 1) % 3 == 0">
                <span v-if="row.id !== '-999'">{{
                  row.scheduleList[dayIndex]?.confirmQuantity || ""
                }}</span>
                <span v-else>{{
                  row.scheduleList[dayIndex]?.confirmQuantity
                }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />
  </div>
</template>

<script setup lang="ts">
import {
  SearchInterface,
  TableResultObject,
  ScheduleList,
} from "./utilejs/interface";
import {
  resolveSearchData,
  objectSpanMethod,
  getDays,
  inConsistent,
} from "./utilejs/index";
import { filterOrder } from "@/utils/commonHooks";
import dayjs from "dayjs";
import request from "@/utils/request";
import { useTable, useDownload, useDictionary } from "@/utils/useTable";

defineOptions({
  name: "MESSRMPURCHASEDEMANDALL",
  inheritAttrs: false,
});

// 初始化搜索参数数据
const searchParam = reactive<SearchInterface>({
  datesSearch: [],
  beginDate: "",
  endDate: "",
  partnerCode: "",
  materialCode: "",
  partnerName: "",
  materialName: "",
  demandStatus: "",
});

// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<SearchInterface>({
  datesSearch: [],
  beginDate: "",
  endDate: "",
  partnerCode: "",
  materialCode: "",
  partnerName: "",
  materialName: "",
  demandStatus: "",
});

const demandStatusOptions = [
  {
    value: "1",
    label: "未反馈",
  },
  {
    value: "2",
    label: "未确认",
  },
  // {
  //   value: "3",
  //   label: "确认",
  // },
  {
    value: "3",
    label: "未允许发货",
  },
];

// 搜索时间变化后处理函数
const intervalDay = ref<number | null>(null);
const intervalDayList = ref<any[]>([]);
function getChangeDate(data: Date[]) {
  if (data) {
    searchParam.beginDate = data[0];
    searchParam.endDate = data[1];
    intervalDay.value = dayjs(data[1]).diff(data[0], "day");
  } else {
    searchParam.beginDate = "";
    searchParam.endDate = "";
    intervalDay.value = null;
  }
}

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
const selectdSingleItem = ref();
function handleSelectionChange(selection: TableResultObject[]) {
  ids.value = selection.map((item: TableResultObject) => item.id);
  // // 当勾选的行数大于1个时  rows代表所勾选的数组
  // if (selection.length > 1) {
  //   const newRows = selection.filter((it: TableResultObject, index: number) => {
  //     if (index == selection.length - 1) {
  //       dataTableRef.value.toggleRowSelection(it, true);
  //       return true;
  //     } else {
  //       dataTableRef.value.toggleRowSelection(it, false);
  //       return false;
  //     }
  //   });
  //   // 赋值给全局变量保存
  //   selectdSingleItem.value = newRows;
  // } else {
  //   // 当勾选行数小于一个时，将选中的值赋值给全局变量保存
  //   selectdSingleItem.value = selection;
  // }
}

// 开始展示逻辑处理
const loading = ref(false);
const tableData = ref([]);
// 点击展示之前
function beforeGetTableList() {
  if (!searchParam.beginDate) {
    ElMessage.error("请选择计划开始和结束日期");
    return;
  } else if (intervalDay.value !== null && intervalDay.value > 30) {
    ElMessage.error("时间跨度不能超过31天");
    return;
  }
  getTableList(1);
}

// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/mes/srmmaterialdemand/getDetailByPeriodForAll",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {
    loading.value = false;
  });
  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  // 时间处理
  intervalDayList.value = getDays(searchParam.beginDate, intervalDay.value);
  // 数据处理
  tableData.value = resolveSearchData(data);
  loading.value = false;
}

// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

// 新增物料弹窗及操作逻辑
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const openAddMaterial = () => {
  addDialog.visible = true;
  addDialog.title = "新增物料";
};
function changeVisible(value: boolean) {
  addDialog.visible = value;
  addGoodsDialog.visible = value;
  feedbackDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    addGoodsDialog.data = {};
    addGoodsDialog.cellId = "";
    addGoodsDialog.id = "";
    feedbackDialog.data = {};
    feedbackDialog.cellId = "";
  }
}

// 新增要货弹窗及操作逻辑
const addGoodsDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  id: "",
});
const openAddGoods = (cellRow?: ScheduleList) => {
  const cellId = cellRow?.id || "";
  let title = "";
  if (cellRow?.demandStatus == 3) {
    title = "查看要货详情";
  } else {
    title = !cellId ? "新增要货" : "修改要货";
  }
  const object = {
    visible: true,
    title: title,
    readvisible: cellRow?.demandStatus == 3 ? true : false,
    beginDate: !cellId
      ? dayjs(searchedParam.beginDate).format("YYYY-MM-DD")
      : "",
    endDate: !cellId ? dayjs(searchedParam.endDate).format("YYYY-MM-DD") : "",
    id: !cellId ? ids.value[0] : "",
    cellId: cellId,
  };
  Object.assign(addGoodsDialog, { ...object });
  console.log("addGoodsDialog", addGoodsDialog);
};

const openAddGoodsByLine = (data: any) => {
  console.log("openAddGoodsByLine", data);
  const cellId = data?.id || "";
  let title = "新增要货";
  const object = {
    visible: true,
    title: title,
    readvisible: false,
    beginDate: !cellId
      ? dayjs(searchedParam.beginDate).format("YYYY-MM-DD")
      : "",
    endDate: !cellId ? dayjs(searchedParam.endDate).format("YYYY-MM-DD") : "",
    id: cellId,
    cellId: "",
  };
  Object.assign(addGoodsDialog, { ...object });
  console.log("addGoodsDialog", addGoodsDialog);
};

// 反馈信息确认弹窗及操作逻辑
const feedbackDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  demandStatus: null,
});
const openFeedbackInfo = (
  cellId = "",
  title = "",
  demandStatus = null,
  contentNumber = null
) => {
  console.log(demandStatus, contentNumber);

  const object = {
    visible: true,
    title: title,
    beginDate: dayjs(searchedParam.beginDate).format("YYYY-MM-DD"),
    endDate: dayjs(searchedParam.endDate).format("YYYY-MM-DD"),
    cellId: cellId,
    demandStatus: demandStatus,
    contentNumber: contentNumber == null ? "" : contentNumber,
  };
  Object.assign(feedbackDialog, { ...object });
};

// 操作前校验是否搜索过
function validIsSearched(type: number) {
  if (!searchedParam.beginDate) {
    ElMessage.error("请先选择计划日期后，再进行操作");
    return;
  } else {
    // 新增物料
    if (type === 1) {
      openAddMaterial();
    }
    // 新增要货
    if (type === 2) {
      openAddGoods();
    }

    // 导入计划
    if (type === 3) {
      weekBatchImport();
    }

    // 批量确认
    if (type === 4) {
      confirmBatch();
    }

    // 批量允许发货
    if (type === 5) {
      sendAbleBatch();
    }
  }
}

// 导入计划
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/mes/srmmaterialdemand/upload", formdata, config)
    .then((res: any) => {
      weekImportRef.value.resCode = res.code;
      if (res.code === 300) {
        errorDataList.value = res.data;
        uploadErrorRef.value.errorBox = true;
      }
    })
    .catch((e) => {
      weekImportRef.value.resCode = 500;
    });
}
const weekBatchImport = () => {
  let params = {
    title: "导入计划",
    tempApi: "", //模板下载
    importApi: weekImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {
      beginDate: searchedParam.beginDate,
      endDate: searchedParam.endDate,
    },
  };
  weekImportRef.value.acceptParams(params);
};

// 导出
const downLoad = () => {
  if (!searchedParam.beginDate) {
    ElMessage.error("请先选择计划日期后，再进行操作");
    return;
  } else {
    useDownload(
      "/mes/srmmaterialdemand/exportAll",
      "采购需求",
      searchParam,
      true,
      ".xls"
    );
  }
};

// 全部确认弹窗
function allConfirm(row: TableResultObject) {
  // console.log("feedbackSure", row);
  ElMessageBox.confirm("请确认，是否继续全部确认操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/mes/srmdemandschedule/confirmAll",
          method: "post",
          data: {
            beginDate: searchedParam.beginDate,
            endDate: searchedParam.endDate,
            id: row.id,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("全部确认成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}

function confirmBatch() {
  ElMessageBox.confirm("请确认，是否继续批量确认操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/mes/srmdemandschedule/confirmBatch",
          method: "post",
          data: {
            beginDate: searchedParam.beginDate,
            endDate: searchedParam.endDate,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量确认成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}

function sendAbleBatch() {
  ElMessageBox.confirm("请确认，是否继续批量允许发货操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/mes/srmdemandschedule/sendAbleBatch",
          method: "post",
          data: {
            beginDate: searchedParam.beginDate,
            endDate: searchedParam.endDate,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量允许发货成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-table__body td.el-table__cell {
    padding: 0;
  }
  .cell {
    padding: 0;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell > :first-child {
    padding: 3px 12px;
  }

  .el-scrollbar__wrap {
    max-height: calc(100vh - 342px);
    overflow-y: scroll;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}
</style>
